# 实例
import json

from pyecharts.charts import Bar
from pyecharts.options import *


class Order:
    date: str
    order_id: str
    money: int
    province: str

    def __init__(self, date, order_id, money, province):
        self.date = date
        self.order_id = order_id
        self.money = money
        self.province = province

    def __str__(self):
        d = {"date": self.date, "order_id": self.order_id, "money": self.money, "province": self.province}
        return json.dumps(d, ensure_ascii=False)


def read_file_lines(file_name: str) -> list[str]:
    with open(file_name, "r", encoding="utf-8") as f:
        lines = f.readlines()
        return lines

# text_file_reader
# json_file_reader

def parse_line1(line: str) -> Order:
    cells = line.strip().split(",")
    return Order(cells[0], cells[1], int(cells[2]), cells[3])


def parse_line2(line: str) -> Order:
    d = json.loads(line.strip())
    return Order(**d)


def calc_date_money(orders: list[Order]) -> dict[str, int]:
    d = {}
    for order in orders:
        if order.date not in d:
            d[order.date] = 0
        d[order.date] += order.money
    return d


def calc_graph(d: dict[str, int]) -> (list[str], list[int]):
    x_data = sorted(d.keys())
    y_data = []
    for date in x_data:
        y_data.append(d[date])
    return x_data, y_data


if __name__ == '__main__':
    lines1 = read_file_lines("data/2011年1月销售数据.txt")
    orders = []
    for line in lines1:
        order = parse_line1(line)
        orders.append(order)

    lines2 = read_file_lines("data/2011年2月销售数据JSON.txt")
    for line in lines2:
        order = parse_line2(line)
        orders.append(order)

    date_money = calc_date_money(orders)
    x_data, y_data = calc_graph(date_money)

    bar = Bar()
    bar.add_xaxis(x_data)
    bar.add_yaxis("销售数据", y_data, label_opts=LabelOpts(is_show=False))
    # bar.set_global_opts(title_opts=TitleOpts())
    bar.render("../output/2011年销售数据.html")
